package com.yanqu.road.dao.impl.servercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class DbInfoDaoImpl extends TempDao {

	public List<DbInfo> getServerDbInfo(int serverId) {
		List<DbInfo> dbInfos = new ArrayList<>();
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "select * from t_s_db_info where serverId = ?";
		try {
			getDb().setConnName(DbNameStrategy.getServerDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setInt(1, serverId);
			rs = call.executeQuery();
			while (rs.next()) {
				parseDbInfo(rs.getString("userDatabase"), dbInfos);
				parseDbInfo(rs.getString("logDatabase"), dbInfos);
				parseDbInfo(rs.getString("configDatabase"), dbInfos);
				parseDbInfo(rs.getString("crossDatabase"), dbInfos);
				parseDbInfo(rs.getString("cross2Database"), dbInfos);
				return dbInfos;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return null;
	}

	private void parseDbInfo(String str, List<DbInfo> dbInfos) {
		if (StringUtils.isNullOrEmpty(str)) {
			return;
		}
		JSONObject jObject = null;
		try {
			jObject = JSONObject.parseObject(str);
			DbInfo info = new DbInfo();
			info.setDbName(jObject.getString("dbname"));
			info.setUserName(jObject.getString("dbuser"));
			info.setIp(jObject.getString("ip"));
			info.setPassword(jObject.getString("dbpassword"));
			info.setPort(jObject.getIntValue("port"));
			info.setConnectionNum(jObject.getIntValue("dbconnection"));
			if(jObject.containsKey("partitionCount")){
				info.setPartitionCount(jObject.getInteger("partitionCount"));
			}
			if(jObject.containsKey("maxConnectionsPerPartition")){
				info.setMaxConnectionsPerPartition(jObject.getInteger("maxConnectionsPerPartition"));
			}
			if(jObject.containsKey("minConnectionsPerPartition")){
				info.setMinConnectionsPerPartition(jObject.getInteger("minConnectionsPerPartition"));
			}
			dbInfos.add(info);
		} catch (Exception e) {
			return;
		}
	}

}
